﻿using System;
using System.Globalization;
using Bookvar.ApplicationModel;
using Bookvar.ObjectModel;
using Bookvar.ObjectModel.Actions.Collaboration;

namespace Bookvar.Collaboration.ClientSide
{
    internal class CollaborationServiceCallback : ICollaborationServiceCallback
    {
        private IExecutionContext context;

        public CollaborationServiceCallback(IExecutionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.context = context;
        }

        #region ICollaborationServiceCallback Members

        public void UserEnter(CollaborationUser user)
        {
            ICollaborationEventsPublisher cp =
                BookvarApplication.Current.ServiceLayer.GetService<ICollaborationEventsPublisher>();

            cp.PublishUserJoined(user);
            Logger.Log(string.Format(CultureInfo.CurrentCulture, "UserEnter {0}", user.Name));
        }

        public void UserLeave(CollaborationUser user)
        {
            ICollaborationEventsPublisher cp =
                BookvarApplication.Current.ServiceLayer.GetService<ICollaborationEventsPublisher>();
            cp.PublishUserLeft(user);

            Logger.Log(string.Format(CultureInfo.CurrentCulture, "UserLeave {0}", user.Name));
        }

        public void DoAction(ActionBase action)
        {
            Logger.Log("CollaborationServiceClient received:  " + action);

            SayAction sayAction = action as SayAction;
            if (sayAction != null)
            {
                sayAction.CollaborationEventsPublisher =
                    BookvarApplication.Current.ServiceLayer.GetService<ICollaborationEventsPublisher>();
            }

            action.Execute(context);
        }

        public void ServerClosed(CollaborationUser host)
        {
            ICollaborationEventsPublisher cp =
                BookvarApplication.Current.ServiceLayer.GetService<ICollaborationEventsPublisher>();
            cp.PublishServerClosed(host);
        }

        #endregion
    }
}